<template>
	<section>
		<!--高级查询-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="advancedQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="200" sortable>
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间" width="200" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门主管" width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" min-width="120" sortable>
			</el-table-column>
      <el-table-column prop="path" label="路径" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="50" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 1" style="color: #11b95c">正常</span>
          <span v-else style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="简介" min-width="200" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger"
                 @click="batchDelete"
                 :disabled="this.sels.length===0"
                 style="float: left;margin: 20px">
        批量删除</el-button>
      <!--分页条-->
      <el-pagination
          style="float: right;margin: 20px"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="pageSizes"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>



		<!--保存界面-->
    <!--
       pros 绑定校验规则名称
       :visible.sync  控制dialog是否显示
       :rules  绑定表单校验规则
       ref="saveForm"  给当前表单取一个别名
    -->
		<el-dialog title="保存"
               :visible.sync="saveFormVisible"
               :close-on-click-modal="false">
			<el-form
          :model="saveForm"
          label-width="80px"
          :rules="saveFormRules"
          ref="saveForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="管理员" prop="manager">
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="e in employees"
                :key="e.id"
                :label="e.username"
                :value="e">
              <span style="float: left">{{ e.username }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">正常</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
				<el-form-item label="简介">
					<el-input type="textarea" v-model="saveForm.intro"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
        <!--@click.native vue在自定义组件中使用原生事件要加上native-->
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">确认</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
/*	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';*/

	export default {
		data() {
			return {
        pageInfo:{
          rows: [],
          total: 0,
        },
        pageSizes:[5, 10, 20, 50],
        //查询对象
        query:{
				  //当前页,默认第一页
          currentPage:1,
          //页面显示数据大小,默认显示5条
          pageSize:5,
          //高级查询关键字
          keyword:""
        },
				listLoading: false,
				sels: [],//列表选中列

        saveFormVisible: false,//新增界面是否显示
        saveLoading: false,
        //校验规则
        saveFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					]
				},
				//新增界面数据
        saveForm:{
          name: '',
          intro:"",
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          nums:0,
          state:null
        },
        employees:[],
        deptTree:[]
			}
		},
		methods: {
			handleCurrentChange(val) {
			  //改变当前显示页数
        this.query.currentPage = val;
        this.getDepartments();
			},
      handleSizeChange(val) {
			  //改变每页显示条数
        this.query.pageSize = val;
        this.getDepartments();
      },
			//获取用户列表
			getDepartments() {
				this.listLoading = false;
				this.$http.post("/department",this.query)
        .then(result => {
          result = result.data;
          this.pageInfo = result.obj;
        })
        .catch(result =>{
          this.$message({
            message: result.message,
            type: 'error'
          });
        })
			},
      advancedQuery(){
        //初始化页面
        this.query.currentPage = 1;
        //加载数据到页面
        this.getDepartments();
      },
			//删除
			handleDel: function (index, row) {
        this.$confirm('数据将无法恢复!', '警告', {
          type: 'warning'
        }).then(() => {
          //弹出加载窗口
          this.listLoading = true;
          this.$http.delete("/department/"+row.id)
              .then(result => {
                //操作成功进入then,关闭加载窗口
                this.listLoading = false;
                result = result.data;
                if(result.success){
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                  //删除完成后刷新页面
                  this.advancedQuery();
                }else{
                  this.$message({
                    message: '删除失败!',
                    type: 'error'
                  });
                }
              })
              .catch(result => {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              })
        }).catch(() => {
          this.$message({
            message: result.message,
            type: 'error'
          });
        });
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        //弹出界面
        this.saveFormVisible = true;
        this.$http.get("/department").then(result =>{
          result = result.data;
          //Object.assign({}, row);数据回显
          //Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象分配到目标对象。它将返回目标对象。
          //Object.assign方法的第一个参数是目标对象，后边的其他参数都是源对象；
          this.saveForm = Object.assign({}, row);
          console.log("数据回显"+this.saveForm);
          //部门经理
          this.getAllEmployee();
          // 父部门回显
          let temp = [];
          if(row.path){
            let array = row.path.split("/");
            for(let i=1;i<array.length-1;i++){
              temp.push(parseInt(array[i]));
            }
          }
          this.saveForm.parent = temp;
          console.log("父部门"+this.saveForm.parent);
          //debugger
          this.getDeptTree();
        }).catch(result =>{

        })
			},
			//显示新增界面
			handleAdd: function () {
        //弹出界面
        this.saveFormVisible = true;
        //初始化
        this.saveForm = {
          name: '',
          intro:"",
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          state:null
        }
        this.getAllEmployee();
        this.getDeptTree();
      },
      // 查询部门树
      getDeptTree(){
        this.$http.get("/department/tree")
            .then(result => {
              result = result.data;
              console.log("部门树");
              console.log(result);
              this.deptTree = result.obj;
            }).catch(result => {
          this.$message({ message: '查询部门树失败',type: 'error'});
        })
      },
      //查询所有员
      getAllEmployee(){
        this.$http.get("/employee")
            .then(result => {
              result = result.data;
              console.log(result)
              // 将获取到的所有的员工信息,赋值给this.employees,因为要来渲染部门经理下拉框的
              this.employees = result.obj;
            })
      },

			//新增
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              //NProgress.start();
              let para = Object.assign({}, this.saveForm);

              console.log("父部门");
              console.log(para);
              // 处理父部门
              if(para.parent){
                para.parent = {"id":para.parent[para.parent.length-1]}
              }
              this.$http.put("/department",para)
                  .then(result => {
                    result = result.data;
                    if(result.success){
                      this.advancedQuery();
                      this.saveLoading = false;
                      this.saveFormVisible = false;
                      this.$message({ message: '保存成功',type: 'success'});
                    }else{
                      this.$message({ message: result.message,type: 'error'});
                    }
                  })
            });
          }
        });
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
      batchDelete: function () {
        //从sels中获取所有被选中的id
        var ids = this.sels.map(item => item.id);
        this.$confirm('数据将无法恢复!', '警告', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //除get请求其他请求传参应该加上requestBody否侧无数据
          this.$http.patch("/department",ids)
              .then(result => {
                //无论成功与否都要关闭加载窗口
                this.listLoading = false;
                //后端返回的数据会被包在data中
                result = result.data;
                if(result.success){
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                  //刷新页面
                  this.advancedQuery();
                }else{
                  this.$message({
                    message: '删除失败!',
                    type: 'error'
                  });
                }
              })
              .catch(result => {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              })
        }).catch(() => {
          this.$message({
            message: result.message,
            type: 'error'
          });
        });
      },


		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>